package services

import (
	"gohub/app/models/permission"
	"gohub/app/models/role"
	"gohub/app/models/roleperms"
	"gohub/app/models/user"
	"gohub/pkg/auth"
	"regexp"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// 获取登录用户相关数据
func GetLoginProfile(c *gin.Context) (map[string]interface{}, error) {
	userModel := auth.CurrentUser(c)
	//fmt.Printf("===== RoleId: %#v\n", userModel.RoleId)
	//获取角色
	roleModel := role.GetRoles(userModel.RoleId)

	// 收集所有权限ID
	allPermissionIDs := make(map[string]struct{})

	//获取权限
	for _, role := range roleModel {
		// 查询角色权限
		rolePerms := roleperms.Get(strconv.Itoa(int(role.ID)))

		// 去重
		for _, pid := range rolePerms.Data {
			pid = strings.TrimSpace(pid)
			if _, exists := allPermissionIDs[pid]; !exists {
				allPermissionIDs[pid] = struct{}{}
			}
		}
	}

	// 分类权限
	var menus, pointsid []string
	pattern := regexp.MustCompile(`^[1-9]-[1-9]$`)
	for pid := range allPermissionIDs {
		if pattern.MatchString(pid) {
			pointsid = append(pointsid, pid)
		} else {
			menus = append(menus, pid)
		}
	}

	// 查询权限详细信息
	//fmt.Printf("===== menus: %#v\n", menus)
	permissions := permission.GetAll(menus)
	//fmt.Printf("===== permissions: %#v\n", permissions)

	menuMarks := make([]string, 0)
	for _, p := range permissions {
		//fmt.Printf("===== p: %#v\n", p)
		//fmt.Printf("===== menuMarks: %v\n", p.PermissionMark)
		menuMarks = append(menuMarks, p.PermissionMark)
	}

	// 1. 查询所有权限数据
	allPermissions := permission.All()
	//fmt.Printf("===== pointsid: %#v\n", pointsid)

	// 2. 收集所有子权限的permissionMark
	points := make([]string, 0)
	for _, pid := range pointsid {
		for _, perm := range allPermissions {
			// 安全访问children字段
			if perm.Children != nil {
				for _, child := range perm.Children {
					//fmt.Printf("===== pid: %#v, childid: %#v\n", pid, child.ID)
					if pid == child.ID {
						if child.PermissionMark != "" {
							//fmt.Printf("===== 功能权限: %#v\n", child)
							points = append(points, child.PermissionMark)
						}
					}
				}
			}
		}
	}

	// 组合数据
	data := map[string]interface{}{
		"id":       userModel.ID,
		"username": userModel.Username,
		"avatar":   userModel.Avatar,
		"permission": map[string]interface{}{
			"menus":  menuMarks,
			"points": points,
		},
		"role": roleModel,
	}
	return data, nil
}

func GetUserDetail(c *gin.Context, uid string) (map[string]interface{}, error) {
	userModel := user.Get(uid)

	//获取角色
	roleModel := role.GetRoles(userModel.RoleId)

	// 组合数据
	data := map[string]interface{}{
		"id":       userModel.ID,
		"username": userModel.Username,
		"avatar":   userModel.Avatar,
		"mobile":   userModel.Mobile,
		"roles":    roleModel,
	}
	return data, nil
}
